﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http.Routing;

namespace OMG.Fill.Frunit.UI
{
    public class CustomConstraint : IHttpRouteConstraint
    {
        public string[] array = new string[] { "GET", "PUT", "DELETE", "POST", "EDIT", "UPDATE", "AUDIT", "DOWNLOAD" };
        public bool match { get; set; }
        private string _id = "id";
        #region IHttpRouteConstraint 成员
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
        {
            if (values == null)
                return true;
            if (!values.ContainsKey(parameterName) || !values.ContainsKey(_id))
                return true;
            var action = values[parameterName].ToString().ToLower();
            if (string.IsNullOrEmpty(action))
            {
                values[parameterName] = request.Method.ToString();
            }
            else if (string.IsNullOrEmpty(values[_id].ToString()))
            {
                var isidstr = true;
                array.ToList().ForEach(x =>
                {
                    if (action.StartsWith(x.ToLower()))
                        isidstr = false;
                });

                if (isidstr)
                {
                    values[_id] = values[parameterName];
                    values[parameterName] = request.Method.ToString();
                }
            }
            return true;
        }
        #endregion
    }
}